package com.ws.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.net.URI;
import java.util.Map;

/**
 * @ClassName NXHttpUtil
 * @Description TODO
 * @Author zhengchenggong
 * @Date 2020/11/27 2:45 下午
 * @Version 1.0
 **/
public class NXHttpUtil {

    public static String doPost(String url, Map<String, String> headers, String paramJson, int timeOut) {

        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));
            //请求头设置
            if (headers != null) {
                for (String key : headers.keySet()) {
                    request.setHeader(key, headers.get(key));
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();//设置请求和传输超时时间
            request.setConfig(requestConfig);
            StringEntity se = new StringEntity(paramJson, ContentType.APPLICATION_JSON);
            request.setEntity(se);
            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                return EntityUtils.toString(response.getEntity(), "utf-8");
            } else {//
                System.out.println("状态码：" + code);
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
